import os
import shutil
from typing import Optional

try:  # local import, safe during PyInstaller runtime
    from app.core.paths import app_root
except Exception:  # pragma: no cover
    def app_root() -> str:
        return os.getcwd()

try:
    import imageio_ffmpeg as iio_ffmpeg
except Exception:  # pragma: no cover
    iio_ffmpeg = None


def get_ffmpeg_exe() -> Optional[str]:
    exe = shutil.which("ffmpeg") or shutil.which("ffmpeg.exe")
    if exe:
        return exe

    # bundled ffmpeg next to dist (PyInstaller) or source assets
    # look in current working dir and app_root
    candidates = [
        os.path.join(os.getcwd(), "ffmpeg", "ffmpeg.exe"),
        os.path.join(os.getcwd(), "assets", "ffmpeg", "ffmpeg.exe"),
        os.path.join(app_root(), "ffmpeg", "ffmpeg.exe"),
        os.path.join(app_root(), "assets", "ffmpeg", "ffmpeg.exe"),
    ]
    for p in candidates:
        if os.path.isfile(p):
            return p

    if iio_ffmpeg is not None:
        try:
            exe = iio_ffmpeg.get_ffmpeg_exe()
            if os.path.isfile(exe):
                return exe
        except Exception:
            return None
    return None


def get_ffprobe_exe() -> Optional[str]:
    exe = shutil.which("ffprobe") or shutil.which("ffprobe.exe")
    if exe:
        return exe

    candidates = [
        os.path.join(os.getcwd(), "ffmpeg", "ffprobe.exe"),
        os.path.join(os.getcwd(), "assets", "ffmpeg", "ffprobe.exe"),
        os.path.join(app_root(), "ffmpeg", "ffprobe.exe"),
        os.path.join(app_root(), "assets", "ffmpeg", "ffprobe.exe"),
    ]
    for p in candidates:
        if os.path.isfile(p):
            return p

    # Try sibling of discovered ffmpeg.exe
    try:
        ffmpeg_exe = get_ffmpeg_exe()
        if ffmpeg_exe:
            sibling = os.path.join(os.path.dirname(ffmpeg_exe), "ffprobe.exe")
            if os.path.isfile(sibling):
                return sibling
    except Exception:
        pass

    # imageio-ffmpeg does not ship ffprobe helper reliably; skip
    return None


